﻿using System.Collections.Generic;
using System.Web.Mvc;
using BookTheBook.Amazon;
using BookTheBook.Data.Model;
using BookTheBook.Web.Helpers;

namespace BookTheBook.Web.Controllers
{
    public class SearchController : Controller
    {
        private static IBookEntitiesProvider _booksProvider;

        public SearchController(IBookEntitiesProvider booksProvider)
        {
            _booksProvider = booksProvider;
        }

        //
        // GET: /Search/
        
        public ActionResult Index()
        {
            return View();
        }

        //
        // POST: /Search/Submit

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Submit(string query)
        {
            const int pageIndex = 1;
            return RedirectToAction("Submit", new {query, pageIndex});
        }

        //
        // Get: /Search/Submit

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Submit()
        {
            string query = Request.QueryString["query"];
            int pageIndex;
            bool success = int.TryParse(Request.QueryString["pageIndex"], out pageIndex);
            pageIndex = success ? pageIndex : 1;

            PaginatedListCollection<Book> booksFound = Search(query, pageIndex);
            return View("Index", booksFound);
        }

        private static PaginatedListCollection<Book> Search(string query, int pageIndex)
        {
            List<Book> searchResults;
            int totalPages = _booksProvider.GetBooksForGivenKeywords(new List<string> { query }, pageIndex, out searchResults);
            var booksToPassToView = new PaginatedListCollection<Book>(searchResults, totalPages, query, pageIndex);
            return booksToPassToView;
        }
    }
}
